<?php
define ( 'BPT_IS_INSTALLED', 1 );
define ( 'BPT_VERSION', '0.1' );

load_plugin_textdomain( 'bpt', false, '/bp-ticketing/includes/languages/' );

if ( !class_exists( 'WPSC_Query' ) )
	return;

if ( !defined( 'BPT_TICKETS_SLUG' ) )
	define ( 'BPT_TICKETS_SLUG', __( 'tickets', 'bpt' ) );

if ( !defined( 'BPT_TICKETS_HISTORY_SLUG' ) )
	define ( 'BPT_TICKETS_HISTORY_SLUG', __( 'purchases', 'bpt' ) );

if ( !defined( 'BPT_REDEEM_SLUG' ) )
	define ( 'BPT_REDEEM_SLUG', __( 'redeem', 'bpt' ) );

if ( !defined( 'BPT_ADMIN_SETTINGS_SLUG' ) )
	define ( 'BPT_ADMIN_SETTINGS_SLUG', __( 'settings', 'bpt' ) );

// The classes file holds all database access classes and functions
require ( dirname( __FILE__ ) . '/bpt-classes.php' );

// The cssjs file should set up and enqueue all CSS and JS files used by the component
require ( dirname( __FILE__ ) . '/bpt-cssjs.php' );

// The templatetags file should contain classes and functions designed for use in template files
require ( dirname( __FILE__ ) . '/bpt-templatetags.php' );

// The filters file should create and apply filters to component output functions
require ( dirname( __FILE__ ) . '/bpt-filters.php' );

/**
 * bpt_is_wpsc_active() 
 *
 * Convenience function for finding out if WordPress e-Commerce is active
 */
function bpt_is_wpsc_active() {
	return defined( 'WPSC_VERSION' );
}

/**
 * bpt_add_admin_menu()
 *
 * This function will add a WordPress wp-admin admin menu for your component under the
 * "BuddyPress" menu.
 */
function bpt_add_admin_menu() {
	global $bp, $menu;

	if ( !$bp->loggedin_user->is_site_admin || !bpt_is_wpsc_active() )
		return false;

	require ( dirname( __FILE__ ) . '/bpt-admin.php' );

	add_action( 'load-store_page_wpsc-buddypressticketing', 'bpt_admin_pages_on_load' );
	add_action( 'admin_init', 'bpt_admin_register_settings' );
	add_submenu_page( 'wpsc-sales-logs', __( 'Ticketing Settings', 'bpt' ), __( 'BuddyPress Ticketing', 'bpt' ), 'manage_options', 'wpsc-buddypressticketing', 'bpt_admin' );
}
add_action( 'admin_menu', 'bpt_add_admin_menu', 11 );  /* wpsc_admin_pages = 10 */

/**
 * bpt_load_template_filter()
 *
 * Custom load template filter; allows user to override these templates in
 * their active theme and replace the ones that are stored in the plugin directory.
 */
function bpt_load_template_filter( $found_template, $templates ) {
	global $bp;

	if ( $bp->current_component != BPT_TICKETS_SLUG )
		return $found_template;

	foreach ( (array) $templates as $template ) {
		if ( file_exists( STYLESHEETPATH . '/' . $template ) )
			$filtered_templates[] = STYLESHEETPATH . '/' . $template;
		else
			$filtered_templates[] = dirname( __FILE__ ) . '/templates/' . $template;
	}

	$found_template = $filtered_templates[0];
	return apply_filters( 'bpt_load_template_filter', $found_template );
}
add_filter( 'bp_located_template', 'bpt_load_template_filter', 10, 2 );

/**
 * bpt_load_template()
 *
 * Loads templates within a template.
 */
function bpt_load_template( $template ) {
	if ( $located_template = apply_filters( 'bp_located_template', locate_template( $template, false ), $template ) )
		load_template( apply_filters( 'bp_load_template', $located_template ) );
}


/********************************************************************************
 * Screen Functions
 *
 * Screen functions are the controllers of BuddyPress. They will execute when their
 * specific URL is caught. They will first save or manipulate data using business
 * functions, then pass on the user to a template file.
 */

function bpt_setup_nav() {
	global $bp, $is_member_page;

	if ( !bp_is_my_profile() )
		return;

	$subnav_url = $bp->loggedin_user->domain . BPT_TICKETS_SLUG . '/';
	bp_core_new_nav_item( array( 'name' => __( 'Ticketing', 'bpt' ), 'slug' => BPT_TICKETS_SLUG, 'screen_function' => 'bpt_screen_ticketing', 'default_subnav_slug' => BPT_TICKETS_HISTORY_SLUG, 'item_css_id' => 'ticketing', 'show_for_displayed_user' => bp_is_my_profile() ) );
	bp_core_new_subnav_item( array( 'name' => __( 'Ticket Purchases', 'bpt' ), 'slug' => BPT_TICKETS_HISTORY_SLUG, 'parent_url' => $subnav_url, 'parent_slug' => BPT_TICKETS_SLUG, 'screen_function' => 'bpt_screen_ticketing', 'position' => 10, 'item_css_id' => 'history', 'show_for_displayed_user' => bp_is_my_profile() ) );
	bp_core_new_subnav_item( array( 'name' => __( 'Redeem Voucher', 'bpt' ), 'slug' => BPT_REDEEM_SLUG, 'parent_url' => $subnav_url, 'parent_slug' => BPT_TICKETS_SLUG, 'screen_function' => 'bpt_screen_redeem', 'position' => 20, 'item_css_id' => 'redeem', 'show_for_displayed_user' => bp_is_my_profile() ) );

	bp_core_new_nav_default( array( 'parent_slug' => BPT_TICKETS_SLUG, 'screen_function' => 'bpt_screen_redeem', 'subnav_slug' => BPT_TICKETS_HISTORY_SLUG ) );
}
add_action( 'bp_setup_nav', 'bpt_setup_nav' );

function bpt_screen_ticketing() {
	do_action( 'bpt_screen_ticketing' );
	bp_core_load_template( apply_filters( 'bpt_screen_ticketing', 'bpt/members/single/bp-ticketing' ) );
}

function bpt_screen_redeem() {
	global $bp, $current_user;

	if ( !isset( $_POST['redeem-code-submit'] ) ) {
		do_action( 'bpt_screen_redeem' );
		bp_core_load_template( apply_filters( 'bpt_screen_redeem', 'bpt/members/single/bp-ticketing' ) );
		return;
	}

  if ( !wp_verify_nonce( $_POST['_wpnonce'], 'redemption' ) ) {
		wp_nonce_ays( '' );
		die();
  }

	$is_code_redeemed = true;

	// Get POST form field and validate.
	if ( !$_POST['redeem-code'] )
		$is_code_redeemed = false;

	if ( !$code = apply_filters( 'bpt_registration_redemption_code', $_POST['redeem-code'] ) )
		$is_code_redeemed = false;

	if ( $is_code_redeemed )
		$is_code_redeemed = bpt_is_ticket_code_valid( $code );

	if ( $is_code_redeemed ) {
		// Send email. This is an example, you'd probably want to remove this and hook into the filter.
		get_currentuserinfo();
		$product_name = bpt_get_product_name( $is_code_redeemed );
		$message = sprintf( "Hello! You have successfully redeemed your ticket for %s.", $product_name );
		$email = array( 'to' => $current_user->user_email,
										'subject' => sprintf( __( "%s - ticket redeemed", 'bpt' ), $product_name ),
										'message' => $message );
		wp_mail( $email['to'], $email['subject'], $email['message'] );

		do_action( 'bpt_screen_redeem_success', $is_code_redeemed, $code );
		bp_core_add_message( __( "Success! You've succesfully claimed your WordCamp ticket. We've emailed you the details.", 'bpt' ) );
		bp_core_redirect( bp_loggedin_user_domain() . '/' . BPT_TICKETS_SLUG );

	} else {
		do_action( 'bpt_screen_redeem_fail' );
		bp_core_add_message( __( "We found a problem with your code. Please check that you typed it correctly and try again.", 'bpt' ), 'error' );
		bp_core_redirect( bp_loggedin_user_domain() . '/' . BPT_TICKETS_SLUG . '/' . BPT_REDEEM_SLUG );
	}
}


/********************************************************************************
 * Ticket Redemption
 *
 * Hook into registration to capture ticket redemption code and redirect to
 * complete ticket details.
 */

function bpt_extend_checkout_form() {
	global $bpt_errors, $wpsc_cart;

	$is_a_ticket_sale = false;
	$ticketing_category = bpt_get_ticketing_category();

	while ( wpsc_have_cart_items() ) {
		wpsc_the_cart_item();

		$categories = (array)$wpsc_cart->cart_item->category_id_list;
		foreach ( $categories as $category ) {
			if ( $category == $ticketing_category ) {
				$is_a_ticket_sale = true;
				$quantity = (int)$wpsc_cart->cart_item->quantity;
				break;
			}
		}

		if ( $is_a_ticket_sale )
			break;
	}

	$wpsc_cart->rewind_cart_items();

	if ( !$is_a_ticket_sale || $quantity < 2 )
		return;
?>
	<tr>
		<td colspan="2">
			<h4><?php _e( "Multiple tickets", 'bpt' ) ?></h4>
			<?php _e( "As you are buying multiple tickets, enter the other recipients' email addresses. We'll email them a redemption code directly.", 'bpt' ) ?>
		</td>
	</tr>

	<tr>
		<td><label><?php _e( "Ticket 1: *", 'bpt' ) ?></label></td>
		<td><?php _e( "Details for this ticket will be sent to your account email address.", 'bpt' ) ?></td>
	</tr>

	<?php for ( $i=0; $i<($quantity-1); $i++ ) : ?>
		<?php $has_error = ( $bpt_errors && isset( $bpt_errors[$i] ) ); ?>

		<tr class="<?php if ( $has_error ) { echo 'validation-error'; } ?>">
			<td><label><?php printf( __( "Ticket %d: *", 'bpt' ), $i+2 ) ?></label></td>
			<td>
				<input type="email" name="bpt[]" class="text" value="<?php if ( $has_error ) { echo esc_attr( $bpt_errors[$i] ); } ?>">
				<p class="validation-error"><?php _e( "Please enter a valid email.", 'bpt' ) ?></p>
			</td>
		</tr>
	<?php endfor; ?>
<?php
}
add_action( 'wpsc_inside_shopping_cart', 'bpt_extend_checkout_form' );

function bpt_extend_checkout_validation( $validation_data ) {
	global $bpt_errors;  // I hate using this but can't find a way to pass variables between the two actions/filters here :(

	if ( !isset( $_POST['bpt'] ) )
		return $validation_data;

	$bpt_errors = array();
	$_POST['bpt'] = (array)$_POST['bpt'];

	for ( $i=0; $i<count( $_POST['bpt'] ); $i++ ) {
		$ticket_email = apply_filters( 'bpt_checkout_ticketing_email', $_POST['bpt'][$i] );

		if ( !$ticket_email || !is_email( $ticket_email ) )
			$bpt_errors[$i] = $ticket_email;
	}

	if ( $bpt_errors )
		$validation_data['is_valid'] = false;

	return $validation_data;
}
add_filter( 'wpsc_checkout_validate_forms', 'bpt_extend_checkout_validation' );

function bpt_create_codes_after_checkout( $sale_data ) {
	if ( !isset( $_POST['bpt'] ) )
		return;

	$codes = array();
	$purchase_id = $sale_data['purchase_log_id'];
	$_POST['bpt'] = (array)$_POST['bpt'];

	for ( $i=0; $i<count( $_POST['bpt'] ); $i++ ) {
		$ticket_email = apply_filters( 'bpt_checkout_ticketing_email', $_POST['bpt'][$i] );

		if ( $ticket_email && is_email( $ticket_email ) )
			$codes[] = array( 'code' => bpt_create_code( $ticket_email, $purchase_id ), 'email' => $ticket_email );
	}

	if ( !$codes )
		return;

	foreach ( $codes as $code )
		wpsc_update_meta( $purchase_id, $code['email'], $code['code'], 'bp_ticketing' );

	do_action( 'bpt_create_codes_after_checkout', $codes, $purchase_id );

	// Send emails. This is an example, you'd probably want to remove this and hook into the filter.
	$product_name = bpt_get_product_name( $purchase_id );
	foreach ( $codes as $code ) {
		$message = sprintf( "Hello! Someone's bought you a ticket for %s. To register for the ticket, please enter the following code onto the Redeem Ticket page at %s. Code: %s", $product_name, site_url(), $code['code'] );

		$email = array( 'to' => $code['email'],
										'subject' => sprintf( __( "%s - redemption code", 'bpt' ), $product_name ),
										'message' => $message );

		$email = apply_filters( 'bpt_filter_redemption_email', $email, $purchase_id );
		wp_mail( $email['to'], $email['subject'], $email['message'] );
	}
}
add_action( 'wpsc_submit_checkout', 'bpt_create_codes_after_checkout', 10, 1 );

function bpt_create_code( $email, $purchase_id ) {
	$hash = md5( time() . $email . time() );
	$code = substr( $hash, 0, 2 ) . 'WC' . date( 'y' ) . substr( $hash, 0, 10 );

	return apply_filters( 'bpt_create_code', strtoupper( $code ), $email, $purchase_id );
}
?>